package com.zhangfuxing.datatools.core;

import com.zhangfuxing.datatools.logger.Log;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author 张福兴
 * @version 1.0
 * @date 2024/10/2
 * @email zhangfuxing1010@163.com
 */
public enum Command {
    EXIT("/exit", p -> {
        System.exit(0);
    }),
    HELP("/help", (Consumer<String>) p -> {
        Log.info("/exit         退出");
        Log.info("/help         帮助");
        Log.info("/save         保存");
        Log.info("/history      查看输入历史记录");
        Log.info("/env          查看当前连接环境");
        throw new RuntimeException();
    }),
    SAVE("/save", p -> {
        return p.substring("/save".length()).trim();
    }),
    ENV("/env", (Consumer<String>) p -> {
        AppConfig config = AppContext.getBean(AppConfig.class);
        Log.info("driverClassName=" + config.getDriverClassName());
        Log.info("url=" + config.getUrl());
        Log.info("username=" + config.getUsername());
        Log.info("password=" + config.getPassword());
        Log.info("driver=" + config.getDriverClassName());
        Log.info("libs=" + config.getLibs());
        throw new RuntimeException();
    }),
    HISTORY("/history", (Consumer<String>) p -> {
        for (String comm : EntryPoint.history) {
            Log.info(comm);
        }
        throw new RuntimeException();
    }),
    CLEAR("/clear", (Consumer<String>) p -> {
        SysUtil.clear();
        CommandReader.inputTips.run();
        throw new RuntimeException();
    }),
    DEFAULT("", String::trim);

    public String command;
    private final Consumer<String> action;
    private Function<String, String> fun;

    Command(String command, Consumer<String> action) {
        this.command = command;
        this.action = action;
    }

    Command(String command, Function<String, String> fun) {
        this(command, c -> {
        });
        this.fun = fun;
    }

    public void execute() {
        EntryPoint.history.add(command);
        action.accept(this.command);
    }

    public static Command parse(String command) {
        if (command == null || command.isEmpty()) {
            return null;
        }
        for (Command c : Command.values()) {
            if (command.startsWith(c.command)) {
                c.command = command;
                return c;
            }
        }
        DEFAULT.command = command;
        return DEFAULT;
    }

    public String getSQL() {
        return this.fun == null ? this.command : this.fun.apply(this.command);
    }
}
